package com.gopay.cashier.security;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.gopay.cashier.web.utils.CashierConfig;

/**
 * 此类用于跳过shiro的检测，传参数给SSO
 * @ShiroPluginService.java
 * @author HJY
 * @2013-8-27 上午10:15:50  www.gopay.com.cn Inc.All rights reserved.
 */
@Service("shiroPluginService")
@SuppressWarnings("all")
public class ShiroPluginService {
    
    private static final String CAS_URL = CashierConfig.get(CashierConfig.CAS_SERVER_URL);
    
    private static final String CASHIER_URL = CashierConfig.get(CashierConfig.CASHIER_URL);
    
    
    private static final String CALLBACK_URL = "callbackUrl";
    
    private static Logger log = LoggerFactory.getLogger("SSO-LOGIN");
    /**
     * 组装登录地址
     * @param request 请求参数
     * @param backUrl 回调地址
     * @return
     */
    public  String getLoginUrl(HttpServletRequest request){
        StringBuffer sb = new StringBuffer();
        String callbackUrl = request.getParameter(CALLBACK_URL);
        if(StringUtils.isBlank(callbackUrl)) {
            log.error("callbackUrl param is null!!");
            return null;
        }
        
        try {
            sb.append(CAS_URL).append("/login?service=");
            sb.append(CASHIER_URL).append(callbackUrl);
            String param = getUrlParam(getParamValues(request));
            if(StringUtils.isNotBlank(param)){
                sb.append("?").append("timeCur=").append(System.currentTimeMillis());
                sb.append(URLEncoder.encode(param, "UTF-8"));
            }
            log.info("SSO_LOGIN_URL:"+sb.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    
    
    private  Map<String, String> getParamValues(HttpServletRequest request){
        Map<String, String> param = new HashMap<String, String>();
        for (Enumeration<String> enumeration = request.getParameterNames(); enumeration.hasMoreElements();) {
            String eleName = (String) enumeration.nextElement();
            String eleValue = request.getParameter(eleName);
            param.put(eleName, eleValue);
            log.info(eleName+"="+eleValue);
        }
        return param;
    }
    
    private  String getUrlParam(Map<String, String> param){
        StringBuffer sb = new StringBuffer();
        if(!param.isEmpty()){
            if(param.containsKey(CALLBACK_URL))
                param.remove(CALLBACK_URL);
            
            for (Iterator<String> keys = param.keySet().iterator(); keys.hasNext();) {
                String key = (String) keys.next();
                String value=param.get(key);
                sb.append("&").append(key).append("=").append(value);
             } 
        }
        return sb.toString();
    }
}